package com.stars.easyms.base.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * <p>className: AbstractEasyMsMethodInterceptor</p>
 * <p>description: 方法拦截器抽象类</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-05-10 15:46
 */
public abstract class AbstractEasyMsMethodInterceptor implements MethodInterceptor {

    private boolean ignoreObjectMethod;

    public AbstractEasyMsMethodInterceptor() {
        this.ignoreObjectMethod = true;
    }

    public AbstractEasyMsMethodInterceptor(boolean ignoreObjectMethod) {
        this.ignoreObjectMethod = ignoreObjectMethod;
    }

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        if (!isAllowEntry(methodInvocation)) {
            return proceed(methodInvocation);
        }

        // 如果是底层Object对象的方法则跳过拦截
        if (ignoreObjectMethod) {

            if (Object.class.equals(methodInvocation.getMethod().getDeclaringClass())) {
                return proceed(methodInvocation);
            }
        }

        return intercept(methodInvocation);
    }

    protected boolean isAllowEntry(MethodInvocation methodInvocation) {
        return true;
    }

    /**
     * 拦截不通过时的执行方法
     *
     * @param methodInvocation 方法拦截对象
     */
    protected Object proceed(MethodInvocation methodInvocation) throws Throwable {
        return methodInvocation.proceed();
    }

    /**
     * 拦截成功后执行的方法
     *
     * @param methodInvocation 方法拦截对象
     */
    protected abstract Object intercept(MethodInvocation methodInvocation) throws Throwable;

}